package org.dh2580.netty.demo.netty.protocol.file;

import java.io.File;
import java.io.RandomAccessFile;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FileRegion;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.CharsetUtil;

/**
 * @Author: hao.deng
 * @Date: 2019/5/7-下午6:32
 */
public class FileServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workderGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workderGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
                            ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                            ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                            ch.pipeline().addLast(new FileServerHandler());
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(10024).sync();

            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workderGroup.shutdownGracefully();
        }
    }

    public static class FileServerHandler extends SimpleChannelInboundHandler<String> {

        private static final String CR = System.getProperty("line.separator");

        @Override
        protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
            File file = new File(msg);

            if (file.exists()) {
                if (!file.isFile()) {
                    ctx.writeAndFlush("Not exist file: " + file + CR);
                    return;
                }


                ctx.write(file + " " + file.length() + CR);

                RandomAccessFile accessFile = new RandomAccessFile(msg, "r");
                FileRegion region = new DefaultFileRegion(accessFile.getChannel(), 0, accessFile.length());

                ctx.write(region);

                ctx.writeAndFlush(CR);

                accessFile.close();

            } else {
                ctx.writeAndFlush("File not found: " + file + CR);
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }

}
